<?php 
declare(strict_types=1);
namespace App\Service;

use App\Dao\CouponDao;
use App\Dao\CouponLogDao;
use App\Dao\LotteryDao;
use App\Exception\BusinessException;
use Hyperf\DbConnection\Db;
use App\Constants\ErrorCode;
use App\Utils\ServerUtil;
use App\Dao\LotteryPrizeDao;
use Hyperf\Utils\Context;


class PrizeService
 {

    /**
     * 奖品列表
     * @return array
     */
    public function list()
    {
        $user = Context::get('jwt_token') ;
        //查询奖品列表
        $list = make(LotteryPrizeDao::class)->getList();
        //获取用户的抽奖次数
        $prizeCount = make(LotteryDao::class)->getPrizeCount($user['account']);

        return ['prize_count'=>$prizeCount, 'pizza_list'=>$list];

    }


    /**
     * 抽奖
     * @return array|mixed
     */
    public function lottery()
    {
        $user = Context::get('jwt_token');
        $lotteryPrizeDao = make(LotteryPrizeDao::class);
        $lotteryDao = make(LotteryDao::class);


        //判断用户有没有抽奖次数
        $prizeCount = $lotteryDao->getPrizeCount($user['account']);
        if($prizeCount < 1){
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '抽奖次数用光了');
        }

        //获取奖品列表
        $pizzaList = $lotteryPrizeDao->getList(8, [
            'lottery_prize.id',
            'lottery_prize.type',
            'lottery_prize.batch_id',
            'lottery_prize.probability',
            'lottery_prize.img',
            'coupon_batch.type as coupon_type',
            'coupon_batch.amount as coupon_amount',
            'coupon_batch.condition_amount'
        ]);

        if(empty($pizzaList)){
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '抽奖奖品未配置');
        }

        //抽奖
        $proArr = array_column($pizzaList, 'probability', 'id');
        $pizzaList = array_column($pizzaList, null, 'id');

        $pizzaId = ServerUtil::getProbRand($proArr);

        if($pizzaList[$pizzaId]['type'] == 1){//红包

            //查看是否有未领取状态的红包
            $where = [
                'coupon.batch_id' => $pizzaList[$pizzaId]['batch_id'],
                'coupon.status' => 0,
            ];
            $couponInfo = make(CouponDao::class)->findCouponByWhere($where);
            if(empty($couponInfo)){

                $info = $lotteryPrizeDao->findByWhere(['type'=>2,'status'=>1,'is_del'=>1], ['id','type','img']);
                if(!empty($info)){
                    $info['coupon_type'] = null;
                    $info['coupon_amount'] = null;
                    $info['condition_amount'] = null;
                    $lotteryDao->addLottery([
                        'openid' => $user['account'],
                        'prize_id' => $info['id'],
                        'remark' => '谢谢惠顾',
                        'remark_desc' => '',
                        'count' => -1,
                        'type' => 2,
                    ]);
                    return $info;
                }

                throw new BusinessException(ErrorCode::ERR_BUESSUS, '抽奖奖品未配置');
            }

            ServerUtil::info( '用户抽奖', [
                'path'=>'/api/pizza_lottery',
                'pizzaList'=>$pizzaList,
                'prizeCount'=> $prizeCount,
                'couponInfo'=> $couponInfo,
                'pizzaId'=>$pizzaId
            ]);

            Db::beginTransaction();
            try{

                //记录抽奖操作
                $lotteryLogId = $lotteryDao->addLottery([
                    'openid' => $user['account'],
                    'prize_id' => $pizzaId,
                    'remark' => '获得'.$pizzaList[$pizzaId]['coupon_amount'].'元红包劵',
                    'remark_desc' => '识别码：' . $couponInfo['unique_num'],
                    'count' => -1,
                    'type' => 2,
                ]);

                if(empty($lotteryLogId)){
                    throw new \Exception('抽奖记录插入失败');
                }

                //发放优惠劵
                $updateData = [
                    'status' => 1,
                    'get_time' => time(),
                    'last_time' => time(),
                    'openid' => $user['account'],
                ];
                if(!make(CouponDao::class)->update(['id'=> $couponInfo['id'], 'status'=>0], $updateData)){
                    //发放失敗
                    throw new \Exception('发放优惠劵失败');
                }

                //添加优惠券日志记录
                $couponLog = [
                    'openid' => $user['account'],
                    'coupon_id' => $couponInfo['id'],
                    'unique_num'=>$couponInfo['unique_num'],
                    'type' => 1,
                    'type_explain' => 3,
                    'lottery_id' => $lotteryLogId,
                    'add_time' => time(),
                    'update_time' => time(),
                    'amount' => $couponInfo['amount'],
                    'start_time' => $couponInfo['start_time'],
                    'end_time' => $couponInfo['end_time'],
                ];
                if(!make(CouponLogDao::class)->add($couponLog)){
                    throw new \Exception('优惠劵日志记录失败');
                }

                Db::commit();
            } catch(\Exception $e){
                Db::rollBack();
                ServerUtil::info('用户抽奖数据库操作出错',['path'=>'/api/pizza_lottery', 'openid'=>$user['account'], 'message'=>$e->getMessage()]);
                throw new BusinessException(ErrorCode::ERR_BUESSUS, '操作失败');
            }

        } else {//谢谢惠顾

            //记录抽奖操作
            $id = $lotteryDao->addLottery([
                'openid' => $user['account'],
                'prize_id' => $pizzaId,
                'remark' => '谢谢惠顾',
                'remark_desc' => '',
                'count' => -1,
                'type' => 2,
            ]);

            if(empty($id)){
                ServerUtil::info('用户抽奖数据库操作出错',['path'=>'/api/pizza_lottery', 'openid'=>$user['account'], 'message'=>'记录抽奖操作失败']);
                throw new BusinessException(ErrorCode::ERR_BUESSUS, '操作失败');

            }

        }

        unset($pizzaList[$pizzaId]['probability']);
        unset($pizzaList[$pizzaId]['batch_id']);

        return $pizzaList[$pizzaId];

    }

    /**
     * 抽奖记录
     * @param $pageSize
     * @param null $page
     * @return array
     */
    public function lotteryLog($page, $pageSize)
    {
        $user = Context::get('jwt_token') ;
        $where = [
            'lottery.openid' => $user['account'],
            'lottery.type' => 2,
            'lottery.is_del' => 1
        ];

        $data = make(LotteryDao::class)->getListPage($where, ['lottery.id','lottery.add_time', 'coupon_log.amount as remark'], $pageSize, $page);

        $info = [
            'data' => ['list'=>[], 'totalItem'=>$data['count']],
            'count' => $data['count']
        ];

        if(!empty($data['list'])){
            foreach ($data['list'] as $k => $v){
                $data['list'][$k]['remark'] = $v['remark'] ?  $v['remark'] . '元红包券' : '谢谢惠顾';
                $data['list'][$k]['add_time'] = ServerUtil::formatDate(strtotime($v['add_time']));
            }
            $info['data']['list'] = $data['list'];
        }

        return $info;
    }
   

 }